import axios from "axios";
import router from "../router";

const http = axios.create({
    baseURL : import.meta.env.VITE_API_URL
})
// 添加请求拦截器
http.interceptors.request.use(function (config:any) {
    if(config.url.includes("user")){
        let token = localStorage.getItem('token')
        if(!token){
            router.push({path:'/user/login'})
            return
        }
        config.headers['Authorization'] = 'Bearer ' + token
        config.headers['content-type'] = 'application/x-www-form-urlencoded'
    }
    if(config.url.includes("info")){
        let token = localStorage.getItem('token')
        if(token){
            config.headers['Authorization'] = 'Bearer ' + token
            config.headers['content-type'] = 'application/x-www-form-urlencoded'
        }
    }
    return config;
}, function (error) {
// 对请求错误做些什么
    console.log(error)
    return Promise.reject(error);
});


// 添加响应拦截器
http.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    
    if(response.data.code == 401){
        router.push({path:'/user/login'})
    }

    return response;
  }, function (error) {
    if(error.status == 401){
        router.push({path:'/user/login'})
    }
    // 对响应错误做点什么
    return Promise.reject(error);
  });

export default http
